import 'package:flutter/material.dart';

import '../../resources/kq_theme_colors.dart';
import '../../theme/kq_theme_manager.dart';

/// 选择切换的长条(均分|滚动|换行)
class KqSelectTag extends StatefulWidget {
  final List<String> tagList;

  /// 选择tag的回调,返回选中 tag 的位置
  final void Function(int)? onSelect;

  /// tag的默认选中值
  final int initPosition;

  /// 是否默认选中
  final bool initChoose;

  /// 布局模式
  final KqSelectTagMode mode;

  /// 背景高度
  final double? bgHeight;

  /// 背景颜色
  final Color? bgColor;

  /// 背景padding
  final EdgeInsetsGeometry? bgPadding;

  /// 文本大小
  final double? textSize;

  /// 文本选中颜色
  final Color? textSelectColor;

  /// 文本普通颜色
  final Color? textNormalColor;

  /// 子项圆角
  final BorderRadiusGeometry? radius;

  /// 子项padding
  final EdgeInsetsGeometry? itemPadding;

  /// 子项margin
  final EdgeInsetsGeometry? itemMargin;

  /// 子项宽度
  final double? itemWidth;

  /// 子项高度
  final double? itemHeight;

  /// 子项选中颜色
  final Color? itemSelectColor;

  /// 子项普通颜色
  final Color? itemNormalColor;

  /// warp的属性(仅换行)
  final double? runSpacing;

  /// 自定义布局(不可以单独使用，必须要有CustomItem，不受模式影响)
  final CustomLayout? customLayout;

  /// 自定义item(可单独使用)
  final CustomItem? customItem;

  const KqSelectTag(
      {Key? key,
      required this.tagList,
      this.onSelect,
      this.initChoose = true,
      this.initPosition = 0,
      this.mode = KqSelectTagMode.share,
      this.bgColor,
      this.textSize,
      this.radius,
      this.itemPadding,
      this.itemMargin,
      this.bgPadding,
      this.bgHeight,
      this.itemWidth,
      this.itemHeight,
      this.textSelectColor,
      this.textNormalColor,
      this.itemSelectColor,
      this.itemNormalColor,
      this.runSpacing,
      this.customLayout,
      this.customItem})
      : super(key: key);

  @override
  State<KqSelectTag> createState() => _KqSelectTagState();
}

class _KqSelectTagState extends State<KqSelectTag> {
  int? position;

  List<Widget> tagLayoutList = [];

  @override
  void initState() {
    super.initState();
    if (widget.initChoose && position == null) {
      position = widget.initPosition;
    }
  }

  @override
  void didUpdateWidget(covariant KqSelectTag oldWidget) {
    if (widget.initChoose && widget.initPosition != oldWidget.initPosition) {
      position = widget.initPosition;
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    tagLayoutList = [];
    for (int i = 0; i < widget.tagList.length; i++) {
      tagLayoutList.add(_chooseItem(i));
    }
    return _chooseLayout();
  }

  Widget _chooseLayout() {
    if (widget.customLayout != null) {
      return _customLayout();
    }
    switch (widget.mode) {
      case KqSelectTagMode.share:
        return _shareLayout();
      case KqSelectTagMode.scroll:
        return _scrollLayout();
      case KqSelectTagMode.warp:
        return _warpLayout();
    }
  }

  Widget _chooseItem(int i) {
    if (widget.customItem != null) {
      return _customItem(i);
    }
    switch (widget.mode) {
      case KqSelectTagMode.share:
        return _shareItem(i);
      case KqSelectTagMode.scroll:
        return _scrollItem(i);
      case KqSelectTagMode.warp:
        return _warpItem(i);
    }
  }

  /// 均分布局
  Widget _shareLayout() {
    return Container(
      height: widget.bgHeight,
      padding: widget.bgPadding ?? EdgeInsets.symmetric(vertical: 10),
      color: widget.bgColor ?? KqThemeColors.bgWhite,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: tagLayoutList,
      ),
    );
  }

  /// 均分项
  Widget _shareItem(int i) {
    return Expanded(
        flex: 1,
        child: GestureDetector(
          onTap: () {
            setState(() {
              position = i;
            });
            widget.onSelect!(i);
          },
          child: Container(
            alignment: Alignment.center,
            child: Container(
              width: widget.itemWidth,
              height: widget.itemHeight,
              decoration: BoxDecoration(
                color: position != null && position == i
                    ? widget.itemSelectColor ??
                        (KqThemeManager.getCommonConfig().mainLightColor ??
                            KqThemeColors.textLightBlue)
                    : widget.itemNormalColor ?? KqThemeColors.textWhite,
                borderRadius:
                    widget.radius ?? BorderRadius.all(Radius.circular(15)),
              ),
              margin: widget.itemMargin,
              padding: widget.itemPadding ??
                  EdgeInsets.symmetric(horizontal: 12, vertical: 4),
              child: Text(
                widget.tagList[i],
                style: TextStyle(
                    fontSize: widget.textSize ?? 12,
                    color: position != null && position == i
                        ? widget.textSelectColor ?? KqThemeColors.textWhite
                        : widget.textNormalColor ?? KqThemeColors.text26),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        ));
  }

  /// 滑动布局
  Widget _scrollLayout() {
    return Container(
      width: double.infinity,
      height: widget.bgHeight ?? 44,
      color: widget.bgColor ?? KqThemeColors.bgWhite,
      padding: widget.bgPadding ?? EdgeInsets.symmetric(vertical: 10),
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: tagLayoutList,
      ),
    );
  }

  /// 滑动项
  Widget _scrollItem(int i) {
    return GestureDetector(
        onTap: () {
          setState(() {
            position = i;
          });
          widget.onSelect!(i);
        },
        child: Container(
          alignment: Alignment.center,
          child: Container(
            width: widget.itemWidth,
            height: widget.itemHeight,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: position != null && position == i
                  ? widget.itemSelectColor ??
                      (KqThemeManager.getCommonConfig().mainLightColor ??
                          KqThemeColors.textLightBlue)
                  : widget.itemNormalColor ?? KqThemeColors.textWhite,
              borderRadius:
                  widget.radius ?? BorderRadius.all(Radius.circular(15)),
            ),
            margin: widget.itemMargin ?? EdgeInsets.symmetric(horizontal: 10),
            padding: widget.itemPadding ??
                EdgeInsets.symmetric(horizontal: 12, vertical: 4),
            child: Text(
              widget.tagList[i],
              style: TextStyle(
                  fontSize: widget.textSize ?? 12,
                  color: position != null && position == i
                      ? widget.textSelectColor ?? KqThemeColors.textWhite
                      : widget.textNormalColor ?? KqThemeColors.text26),
              textAlign: TextAlign.center,
            ),
          ),
        ));
  }

  /// 换行布局
  Widget _warpLayout() {
    return Container(
      width: double.infinity,
      height: widget.bgHeight,
      color: widget.bgColor ?? KqThemeColors.bgWhite,
      padding: widget.bgPadding ?? EdgeInsets.symmetric(vertical: 10),
      child: Wrap(
        alignment: WrapAlignment.spaceEvenly,
        runSpacing: widget.runSpacing ?? 10,
        children: tagLayoutList,
      ),
    );
  }

  /// 换行项
  Widget _warpItem(int i) {
    return GestureDetector(
        onTap: () {
          setState(() {
            position = i;
          });
          widget.onSelect!(i);
        },
        child: Container(
          width: widget.itemWidth,
          height: widget.itemHeight,
          decoration: BoxDecoration(
            color: position != null && position == i
                ? widget.itemSelectColor ??
                    (KqThemeManager.getCommonConfig().mainLightColor ??
                        KqThemeColors.textLightBlue)
                : widget.itemNormalColor ?? KqThemeColors.textWhite,
            borderRadius:
                widget.radius ?? BorderRadius.all(Radius.circular(15)),
          ),
          margin: widget.itemMargin ?? EdgeInsets.symmetric(horizontal: 10),
          padding: widget.itemPadding ??
              EdgeInsets.symmetric(horizontal: 12, vertical: 4),
          child: Text(
            widget.tagList[i],
            style: TextStyle(
                fontSize: widget.textSize ?? 12,
                color: position != null && position == i
                    ? widget.textSelectColor ?? KqThemeColors.textWhite
                    : widget.textNormalColor ?? KqThemeColors.text26),
            textAlign: TextAlign.center,
          ),
        ));
  }

  /// 自定义布局
  Widget _customLayout() {
    if (widget.customLayout != null) {
      return widget.customLayout!();
    }
    return Container();
  }

  /// 自定义项
  Widget _customItem(int i) {
    if (widget.customItem != null) {
      if (widget.mode == KqSelectTagMode.share && widget.customLayout == null) {
        return Expanded(
            child: GestureDetector(
                onTap: () {
                  setState(() {
                    position = i;
                  });
                  widget.onSelect!(i);
                },
                child: widget.customItem!(i, position, widget.tagList[i])));
      } else {
        return GestureDetector(
            onTap: () {
              setState(() {
                position = i;
              });
              widget.onSelect!(i);
            },
            child: widget.customItem!(i, position, widget.tagList[i]));
      }
    }
    return Container();
  }
}

/// 布局模式
enum KqSelectTagMode {
  /// 均分
  share,

  /// 滚动
  scroll,

  /// 换行
  warp
}

/// 自定义布局
typedef CustomLayout = Widget Function();

/// 自定义item
typedef CustomItem = Widget Function(
    int position, int? selectPosition, String text);
